package com.tongji.quickCRUDQ.dao.jdbc;

import java.util.ArrayList;
import java.util.List;

import com.tongji.quickCRUDQ.dao.AppUserDao;
import com.tongji.quickCRUDQ.define.Row;
import com.tongji.quickCRUDQ.model.CommonBean;

public class AppUserDaoJdbc extends BaseDaoJdbc implements AppUserDao {
	String tableName = "APP_USER";

	String beanName = "appUser";

	public CommonBean createAppUser() {
		CommonBean appUsers = this.createBean(tableName, beanName);
		return appUsers;
	}

	public CommonBean findAppUserById(String id) {
		CommonBean appUsers = this.createAppUser();
		String sql = "select * from APP_USER where id=?";
		List data = this.getCommonDao().select(sql, new String[] { id });
		appUsers.addData(data);
		return appUsers;
	}

	public CommonBean findAllAppUsers() {
		CommonBean appUsers = this.createAppUser();
		String sql = "select * from APP_USER ";
		List data = this.getCommonDao().select(sql, new String[] {});
		appUsers.addData(data);
		return appUsers;
	}

	public void insertAppUser(CommonBean appUserBean) {
		List data = appUserBean.getData();
		Row row = this.getRow(tableName);
		this.getCommonDao().templateBatchInsert(row, data, this.getIdGenerator());
	}
	
	public void batchAccount(CommonBean appUserBean, String[] roleIds){
		insertAppUser(appUserBean);
		String sql="insert into user_role(id,user_id,role_id) values(dbo.get_seq(),?,?)";
		List params=new ArrayList();
		int n1=appUserBean.getSize();
		for (int i = 0; i < n1; i++) {
			String user_id=appUserBean.getId(i);
			for (int j = 0; j < roleIds.length; j++) {
				String[] param=new String[]{user_id,roleIds[j]};
				params.add(param);
			}
		}
		this.getCommonDao().batchUpdateRecord(sql, params);
	}
	
	

	public boolean checkUserPassword(String userName, String oldPassword) {
		String sql="select * from app_user where username=? and password=?";
		List data=this.getCommonDao().select(sql, new String[]{userName,oldPassword});
		return data.size()==1;
	}

	public void updatePassword(String userName, String newPassword) {
		String sql="update app_user set password=? where username=?";
		this.getCommonDao().updateRecord(sql, new String[]{newPassword,userName});
	}

}
